<template>
  <el-dialog
    width="35%"
    :title="title"
    :visible.sync="isShow"
    :destroy-on-close="true"
    :modal-append-to-body="false"
    :before-close="handleClose">
    <el-form class="form"
      size="mini" :model="form"
      ref="sessionWindowForm" label-position="top">
      <el-form-item :label="isExpandBtn ? '入口名称' : '按钮名称'" v-if="isShowDialogName">
        <el-input :maxLength="4" v-model="form.name" placeholder="请输入按钮名称，为空不显示，最多4字符"></el-input>
      </el-form-item>
      <el-form-item :label="isExpandBtn ? '入口图片' : '按钮图片'">
        <div v-if="initConfig && form.imgUrl" class="btnImg" style="padding:5px" :class="{btnImgBoder: isExpandBtn}">
          <img :src="initConfig + form.imgUrl" alt="">
        </div>
        <icon-svg :icon-class="'tupian'" class="btnImg" v-else></icon-svg>
        <el-upload
          class="upLoad"
          :show-file-list="false"
          accept=".jpg, .gif, .png, .bmp"
          action=""
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :before-upload="beforeUpload"
          :http-request="uploadRequest">
          <span>上传图片</span>
        </el-upload>
        <span v-if="isShowDelBtn()">
          <span class="line"></span>
          <span class="delImg" @click="delSystemImgFun()">删除</span>
        </span>
      </el-form-item>
      <el-form-item label="事件" v-if="isExpandBtn">
        <m7Select
          size="mini"
          v-model="form.eventName"
          :options="eventOpt"
          filterable
          @change="expandBtnChange"
          :defaultProps="{ label: 'name', value: '_id' }"
          :multiple="false">
        </m7Select>
      </el-form-item>
      <el-form-item label="自定义事件参数" v-if="isExpandBtn && form.eventName === 'customEvent'">
        <el-input v-model="form.eventParame" placeholder="请输入自定义事件参数，用于标识"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelFun()">取 消</el-button>
      <el-button type="primary" @click="saveFun()">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { CommonModule } from '@/store/modules/common'
import { uploadQiniu } from '@/utils/upload'
@Component({
  name: 'setMessageOrImg'
})
export default class SetMessageOrImg extends Vue {
  @Prop({ default: () => '', type: String }) private title
  @Prop({ default: () => false, type: Boolean }) private isShow
  @Prop({ default: () => '', type: String }) private initConfig
  @Prop() private btnObj: any
  @Prop({ default: () => false, type: Boolean }) private isShowDialogName
  @Prop({ default: () => false, type: Boolean }) private isExpandBtn
  private $message: any

  private eventOpt = [
    { name: '拍摄', _id: 'shooting' },
    { name: '选图片', _id: 'photo' },
    { name: '自定义事件', _id: 'customEvent' }
  ]

  private form = {
    name: '',
    imgUrl: '',
    eventParame: '',
    eventName: 'shooting'
  }

  private fileName = ''

  private uploadSuccess (data: any) {
    this.form.imgUrl = data.key ? `/${data.key}` : ''
  }

  private uploadError () { // 上传失败
    this.$message({ message: '图片上传失败，请重新选择图片上传', type: 'error' })
  }

  private uploadRequest (request: any) { // 七牛上传
    uploadQiniu({ type: 'im', fileName: this.fileName }, request)
  }

  private isShowDelBtn () {
    if (this.initConfig && this.form.imgUrl) {
      if (['/4000345/im/20210705175148/1625478708527/8df2a53dcfe049d5ad2a1cfe27fd9908/wxsdkphoto.png',
        '/4000345/im/20210705175107/1625478667684/041f79b5facc4d77b58e2846c3bb5a84/wxsdkshooting.png',
        '/4000345/im/20210705174954/1625478594766/c16d401f88aa4b5fadaa6aebb61fcd04/wxsdkfile.png'].includes(this.form.imgUrl)) {
        return false
      } else {
        return true
      }
    } else {
      return false
    }
  }

  private expandBtnChange () {
    if (!this.isShowDelBtn()) {
      if (this.form.eventName === 'photo') {
        this.form.imgUrl = '/4000345/im/20210705175148/1625478708527/8df2a53dcfe049d5ad2a1cfe27fd9908/wxsdkphoto.png'
      } else if (this.form.eventName === 'shooting') {
        this.form.imgUrl = '/4000345/im/20210705175107/1625478667684/041f79b5facc4d77b58e2846c3bb5a84/wxsdkshooting.png'
      }
    }
  }

  private beforeUpload (file: any) { // 图片上传之前
    this.fileName = file.name.replace(/\s/g, '')
    if (file.size / 1024 / 1024 > 3) {
      this.$message({ message: '图片大小不能超过3M', type: 'error' })
      return false
    }
    if (!this.isExpandBtn) {
      // 限制图片上传宽高。
      const isSize = new Promise<void>((resolve, reject) => {
        const url = window.URL || window.webkitURL
        const img = new Image()
        img.onload = () => {
          const valid = img.width === 80 && img.height === 80
          // eslint-disable-next-line prefer-promise-reject-errors
          valid ? resolve() : reject()
        }
        img.src = url.createObjectURL(file)
      }).then(() => {
        return file
      }, () => {
        this.$message.error('上传文件的图片大小不合符标准,宽需要等于80px，高需要等于80px')
        // eslint-disable-next-line prefer-promise-reject-errors
        return Promise.reject()
      })
      return isSize
    }
  }

  private cancelFun () {
    this.$emit('cancelFun')
  }

  private handleClose () {
    this.$emit('cancelFun')
  }

  private saveFun () {
    if (this.isExpandBtn) {
      if (!this.form.name) {
        this.$message.error('请输入入口名称')
        return false
      }
      if (!this.form.imgUrl) {
        this.$message.error('请选择入口图片')
        return false
      }
      if (this.form.eventName === 'customEvent' && !this.form.eventParame) {
        this.$message.error('请输入自定义参数')
        return false
      }
      this.$emit('messageOrImgSave', this.form)
    } else {
      if (this.form.name || this.form.imgUrl) {
        this.$emit('messageOrImgSave', this.form)
      } else {
        this.$message.error('请输入内容')
      }
    }
  }

  private delSystemImgFun () {
    const sendData = { data: [{ key: this.form.imgUrl, bucket: 'v7-fs-im' }] }
    const actionData = { url: '/base/action/qiniu/delete', method: 'POST', data: sendData }
    CommonModule.publicAction(actionData).then(res => {
      if (res && res.success) {
        if (this.isExpandBtn) {
          switch (this.form.eventName) {
            case 'photo':
              this.form.imgUrl = '/4000345/im/20210705175148/1625478708527/8df2a53dcfe049d5ad2a1cfe27fd9908/wxsdkphoto.png'
              break
            case 'shooting':
              this.form.imgUrl = '/4000345/im/20210705175107/1625478667684/041f79b5facc4d77b58e2846c3bb5a84/wxsdkshooting.png'
              break
            case 'file':
              this.form.imgUrl = '/4000345/im/20210705174954/1625478594766/c16d401f88aa4b5fadaa6aebb61fcd04/wxsdkfile.png'
              break
            default:
              this.form.imgUrl = ''
          }
        } else {
          this.form.imgUrl = ''
        }
      }
    })
  }

  @Watch('btnObj', { immediate: true })
  private btnObjChange (newObj) {
    const { name, imgUrl, eventName, eventParame } = this.btnObj
    this.form = {
      eventParame,
      name,
      eventName: eventName || 'shooting',
      imgUrl
    }
  }
}
</script>
<style lang="stylus" scoped>
  .btnImg
    border-radius 50%
    display inline-block
    vertical-align middle
    width 40px
    height 40px
    margin-bottom 5px
    border 1px solid $border-main
    img
      width 100%
      height 100%
  .btnImgBoder
    border-radius 0
  .btnImg.V7_iconfont
    font-size 40px
    color #008BEE
    line-height 40px
    vertical-align middle
  .upLoad
    display inline-block
    margin 0px 10px
    span
      font-size 12px
      color #008BEE
  .delImg
    font-size 12px
    color #FC6B5C
    margin-left 9px
    display inline-block
    cursor pointer
  .adviceColor
    color #767E91
  .line
    width 1px
    height 9px
    background #008BEE
    margin-left 9px
    opacity 0.3
    display inline-block
</style>
